﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lextm.SharpSnmpLib;
using System.Threading;

namespace SManage.TraceEngine
{
    public static class SyncDispatcher
    {
        private static DeviceDiscoverer _discoverer;
        private static SyncEngine _engine;
        private static SyncTaskPool _taskPool;
        public static event EventHandler<DiscoverFinishedEventArgs> Finished;

        public static void Default() {
            Default(VersionCode.V2);
        }

        public static void Default(VersionCode version) {
            _engine = new SyncEngine();
            _taskPool = SyncTaskPool.Default;
            _discoverer = new DeviceDiscoverer(version);
            InitDiscoverer();
            ThreadPool.QueueUserWorkItem(_ => {
                _discoverer.Run();             
            });
        }

        private static void InitDiscoverer() { 
            _discoverer.FoundSyncItem += (o, e) => {
                _taskPool.Add(e.Item);
            };
            _discoverer.DiscoverFinished += (o, e) => {
                OnFinished(new DiscoverFinishedEventArgs());
                _engine.Start();
            };
        }

        private static void OnFinished(DiscoverFinishedEventArgs e) {
            var handle = Interlocked.CompareExchange(ref Finished, null, null);
            if (handle != null) {
                handle(null, e);
            }
        }

        public static SyncEngine Engine {
            get { return _engine; }
        }

        public static DeviceDiscoverer Discoverer {
            get { return _discoverer; }
        }

        public static SyncTaskPool TaskPool {
            get {
                return _taskPool;
            }
        }
    }
}
